# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


import datetime
import httplib
import hashlib
import urllib
import random
import json

OneDayDelta = datetime.timedelta(days=1)

def getOnDayBoolean(r, location=datetime.datetime.now().date()):
    """
    过滤所需统计的数据
    :param r:
    :param location:
    :return:
    """
    rDate = r['recordDate']
    rDate += datetime.timedelta( hours=16 )
    # 然后就是比较
    if isinstance(location,datetime.datetime):
        location = location.date()
    if rDate == location:
        return True
    else:
        return False


def getIsNewBoolean(r, location=datetime.datetime.now( ).date( )):
    """
    判断课程是否是新课程
    :param r:
    :param location:
    :return:
    """
    pDate = (datetime.datetime( r['publishTime'].year, r['publishTime'].month, r['publishTime'].day, 0, 0,
                                0 ) + datetime.timedelta( days=60 )).date( )
    if pDate > location or pDate == location:
        return True
    else:
        return False

def checkIsOnDay(x, T):
    """
    判断是否是前后相差一天的数据
    :param x:
    :param T:
    :return:
    """
    dayData = x[1]
    preXRecordDate = datetime.datetime( dayData[0][0].year, dayData[0][0].month, dayData[0][0].day, 0, 0, 0 )
    endXRecordDate = dayData[1][0]
    if (preXRecordDate + datetime.timedelta( days=T )).date( ) == endXRecordDate:
        return True
    else:
        return False

def transZH2EN(zhStr):
    """
    调用接口进行中文到英文翻译
    :param zhStr:
    :return:
    """
    appid = '20180129000119389'
    secretKey = 'xb04eiABAJzBv9kytBLF'


    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = zhStr.encode()
    fromLang = 'zh'
    toLang = 'en'
    salt = random.randint(32768, 65536)
    try:
        sign = appid+q+str(salt)+secretKey
        m1 = hashlib.md5()
        m1.update(sign)
        sign = m1.hexdigest()
        myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
        httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        #response是HTTPResponse对象
        response = httpClient.getresponse()
        if response.status == 200:
            resultsStr = response.read()
            if resultsStr:
                resultsOBJ = json.loads(resultsStr)
                if 'trans_result' in resultsOBJ:
                    return resultsOBJ['trans_result'][0]['dst']
                else:
                    return ""
            else:
                return ""
        else:
            return ""
    except Exception, e:
        print e

